package com.siwei.mes.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.siwei.mes.common.dataSource.DataSourceNames;
import com.siwei.mes.common.dataSource.DynamicDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author summer
 * @version 1.0
 * @date 2020/12/28
 * @Description 多数据源配置
 */
@Slf4j
@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.druid.primary")
    public DataSource primaryDataSource() {
        /**注册主数据库*/
        return new DruidDataSource();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.laboratory")
    public DataSource laboratoryDataSource() {
        /**注册实验室数据库*/
        return new DruidDataSource();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.tgl")
    public DataSource tglDataSource() {
        /**注册实验室数据库*/
        return new DruidDataSource();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource primaryDataSource, DataSource laboratoryDataSource, DataSource tglDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DataSourceNames.PRIMARY, primaryDataSource);
        targetDataSources.put(DataSourceNames.LABORATORY, laboratoryDataSource);
        targetDataSources.put(DataSourceNames.TGL, tglDataSource);
        /**还有数据源,在targetDataSources中继续添加*/
        log.info("初始化DataSources成功,个数：{}", targetDataSources.size());
        return new DynamicDataSource(primaryDataSource, targetDataSources);
    }
}
